package com.studyroom.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.studyroom.common.Result;
import com.studyroom.entity.Order;
import com.studyroom.service.OrderService;
import com.studyroom.dto.SearchDTO;
import com.studyroom.utils.JwtTokenUtil;
import com.studyroom.common.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/orders")
@PreAuthorize("hasRole('ADMIN')")
public class AdminOrderController {

    private static final Logger log = LoggerFactory.getLogger(AdminOrderController.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @PostMapping("/search")
    public Result<IPage<Order>> search(@RequestBody SearchDTO params) {
        return Result.success(orderService.search(params));
    }

    @GetMapping("/{id}")
    public Result<Order> getOrderDetail(@PathVariable Long id) {
        return Result.success(orderService.getOrderDetail(id));
    }

    @PutMapping("/{id}/status")
    public Result<Boolean> updateStatus(
            @PathVariable Long id,
            @RequestBody Map<String, Integer> params) {
        return Result.success(orderService.updateOrderStatus(id, params.get("status")));
    }

    @GetMapping("/latest")
    public Result<List<Order>> getLatestOrders(
            @RequestHeader("Authorization") String token) {
        String username = jwtTokenUtil.extractUsername(token.substring(7));
        List<Order> orders = orderService.getLatestOrders(username);
        if (!orders.isEmpty()) {
            Order firstOrder = orders.get(0);
            log.debug("Latest order data:");
            log.debug("- createdAt: {}", firstOrder.getCreatedAt());
            log.debug("- createdAt type: {}", firstOrder.getCreatedAt().getClass().getName());
        }
        return Result.success(orders);
    }

    @DeleteMapping("/{id}")
    public Result<?> deleteOrder(@PathVariable Long id) {
        try {
            orderService.deleteOrder(id);
            return Result.success("订单删除成功");
        } catch (Exception e) {
            return Result.error("删除失败: " + e.getMessage());
        }
    }
} 